function sm = dwfilt(signal, order)
  dwt = repmat(Inf, 1, 31);
  for window = 5:2:31
    sm = sgolayfilt(signal, order, window);
    dwt(window) = dw(signal, sm);
    if dwt(window) < 1
      break;
    endif
  endfor

  [d, window] = min(abs(dwt - 2));
  if ( window <= order )
    sm = signal;
  else
    sm = sgolayfilt(signal, order, window); # redo smoothing with the optimal window
  endif
endfunction
